#include <stdio.h>      
#include <sys/socket.h> 
#include <arpa/inet.h> 
#include <stdlib.h>     
#include <unistd.h>     
#include <string.h>
#include <time.h>

#define RCVBUFSIZE 51200

void wait ( int seconds )
{
  clock_t endwait;
  endwait = clock () + seconds * CLOCKS_PER_SEC ;
  while (clock() < endwait) {}
}


int main(int argc, char *argv[])
{
	int sock;                       
	struct sockaddr_in servAddr; 
	unsigned short servPort;   
	char *servIP;                    
	char *string;               
	char buffer[RCVBUFSIZE];
    char recvbuffer[256] = "";
	unsigned int stringLen;    
	int bytesRcvd, totalBytesRcvd;   

	if (argc != 4)
	{
		fprintf(stderr, "Usage: %s <Port> <time - seconds> <1 - if sync | 0 - if async>\n", argv[0]);
		exit(1);
	}

	servIP = "127.0.0.1";    
	servPort = atoi(argv[1]); 
    int t = atoi(argv[2]);
    int sync = atoi(argv[3]);
	
	if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
	{
		printf("create socket failed");	    
		return -1;
	}

	servAddr.sin_family      = AF_INET;            
	servAddr.sin_addr.s_addr = inet_addr(servIP); 
	servAddr.sin_port        = htons(servPort); 

	if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
	{
		printf("connect failed");	    
		return -1;
	}
    
    if (sync == 0) 
    {
        for (int i = 0; i < 10; ++i) {
            if (send(sock, buffer, RCVBUFSIZE, 0) != RCVBUFSIZE)
            {
                printf("send failed");	    
                return -1;
            }
            wait(t);
            if ((bytesRcvd = recv(sock, recvbuffer, 255, 0)) <= 0)
            {
                printf("recv failed");	    
                return -1;
            } 
            //printf("Received: %s\n", recvbuffer); 
            /*if ((bytesRcvd = recv(sock, recvbuffer, 255, 0)) <= 0)
            {
                printf("recv failed");	    
                return -1;
            } 
            buffer[bytesRcvd] = '\0';  
            printf("Received: %s", buffer);*/  
        }
    } else {
        for (int i = 0; i < 10; ++i) {
            if (send(sock, buffer, RCVBUFSIZE, 0) != RCVBUFSIZE)
            {
                printf("send failed");	    
                return -1;
            }
            while (strcmp(recvbuffer, "Done!") != 0) 
            {
                if ((bytesRcvd = recv(sock, recvbuffer, 255, 0)) <= 0)
                {
                    printf("recv failed");	    
                    return -1;
                } 
                recvbuffer[bytesRcvd] = '\0';  
            }
            //printf("Received: %s\n", recvbuffer); 
            wait(t); 
        }
    }

	//printf("\n");   
wait(2);
	close(sock);
	return 0;
}
